<?php

namespace App\Http\Controllers;

use App\Models\BusinessIndex;
use App\Models\BusinessType;
use App\Models\IndexData;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class InputController extends Controller
{
    public function index()
    {
        $business_type  = BusinessType::get();
        $business_index = BusinessIndex::get();
        $auth = $this->getAuth();
        return view('input.input', compact('business_type', 'business_index', 'auth'));
    }

    /**
     * 添加指标名称
     * @return InputController|Response
     */
    public function addIndexName()
    {
        if(!$this->getAuth()) {
            return $this->setJson(400, '权限不足');
        }
        $type_id = $this->request->input('type_id', 0);
        $name    = $this->request->input('name', '');
        if (intval($type_id) <= 0 || empty($name)) {
            return $this->setJson(100, '参数有误');
        }
        $check = BusinessIndex::where('name', $name)->where('type_id', $type_id)->first();
        if ($check) {
            $bool = BusinessIndex::where('id', $check->id)->update(['name' => $name]);
            if ($bool) {
                return $this->setJson(0, '更新成功', $check->id);
            }
        } else {
            $indexObj = new BusinessIndex();
            $indexObj->type_id = $type_id;
            $indexObj->name = $name;
            $bool = $indexObj->save();
            if ($bool) {
                //向指标里插入数据
                $days = IndexData::distinct()->select('at')->where('type_id', $type_id)->lists('at');
                if ($days) {
                    foreach ($days as $at) {
                        $indexDataObj = new IndexData();
                        $indexDataObj->type_id = $type_id;
                        $indexDataObj->index_id = $indexObj->id;
                        $indexDataObj->at = $at;
                        $indexDataObj->value = 0;
                        $indexDataObj->save();
                    }
                }
                return $this->setJson(0, '添加成功', $indexObj->id);
            }
        }
        return $this->setJson(400, '添加失败');
    }

    /**
     * 添加指标数据
     * @return InputController|Response
     */
    public function addIndexData()
    {
        if(!$this->getAuth()) {
            return $this->setJson(400, '权限不足');
        }
        $at          = $this->request->input('at', '');
        $type_id     = $this->request->input('type_id', 0);
        $index_ids   = $this->request->input('index_id', []);
        $values      = $this->request->input('value', []);
        $index_value = [];
        if (count($index_ids) <= 0 || count($values) <= 0 || intval($type_id) <= 0 || empty($at)) {
            return $this->setJson(300, '参数有误');
        }
        foreach ($index_ids as $key => $val) {
            if (isset($values[$key])) {
                IndexData::updateOrCreate(['at' => $at, 'index_id' => $val, 'type_id' => $type_id], ['value' => $values[$key]]);

            }
        }
        return $this->setJson(0, '操作成功', $index_value);
    }

    /**
     * 获取指标名称 列表
     * @return InputController|Response
     */
    public function getIndexNameList()
    {
        $type_id = $this->request->input('type_id', 0);
        if (intval($type_id) <= 0) {
            return $this->setJson(0, '参数异常');
        }
        $list = [];
        $data = BusinessIndex::where('type_id', $type_id)->get();
        foreach ($data as $item) {
            $list[] = [
                'id'    => $item->id,
                'name'  => $item->name,
                'value' => '',
            ];
        }
        return $this->setJson(0, 'ok', ['list' => $list]);
    }

    /**
     * 获取列表
     * @return InputController|Response
     */
    public function getIndexDataList()
    {
        $type_id = $this->request->input('type_id', 0);
        if (intval($type_id) <= 0) {
            return $this->setJson(0, '参数异常');
        }
        $list = $this->getIndexDataTable($type_id);
        return $this->setJson(0, 'ok', ['list' => $list]);
    }

    //编辑
    public function getIndex()
    {
        if(!$this->getAuth()) {
            return $this->setJson(400, '权限不足');
        }
        $type_id = $this->request->input('type_id', 0);
        $at      = $this->request->input('at', '');
        if (intval($type_id) <= 0 || empty($at)) {
            return $this->setJson(0, '参数异常');
        }
        $list = $this->getEditIndexData($type_id, $at);
        return $this->setJson(0, 'ok', ['list' => $list]);

    }

    /*
     * 获取编辑行数据
     */
    function getEditIndexData($type_id, $at)
    {
        //获取列头
        $business_index = BusinessIndex::where('type_id', $type_id)->get();
        foreach ($business_index as $item) {
            $index_name_ids[$item->id] = $item->name;
        }
        $data            = IndexData::where('type_id', $type_id)->where('at', $at)->get();
        $list = [];
        foreach ($data as $item) {
            $list[$item->getBusinessIndexOne->id] = [
                'id'    => $item->getBusinessIndexOne->id,
                'name'  => $item->getBusinessIndexOne->name,
                'value' => intval($item->value) > 0 ? $item->value : '',
            ];
        }
        return $list;
    }

    /**
     * 拼出表格,列转横,横转列
     * @param $type_id
     * @return array
     */
    function getIndexDataTable($type_id)
    {
        $head       = $body = [];
        $head[]     = '创建时间';
        $head[]     = '更新时间';
        $index_list = $index_name_ids = [];
        //获取列头
        $business_index = BusinessIndex::where('type_id', $type_id)->get();
        foreach ($business_index as $item) {
            $index_name_ids[$item->id] = $item->name;
        }

        $index_data = IndexData::orderBy('at', 'desc')
            ->orderBy('index_id')
            ->where('type_id', $type_id)
            ->get();
        foreach ($index_data as $item) {
            $index_list[$item->at][$item->index_id]['value']      = intval($item->value) > 0 ? $item->value : '-';
            $index_list[$item->at][$item->index_id]['created_at'] = $item->created_at->toDateTimeString();
            $index_list[$item->at][$item->index_id]['updated_at'] = $item->updated_at->toDateTimeString();
        }
        $head = array_merge($index_name_ids, $head);
        array_unshift($head, '月份');
        array_push($head, '操作');
        foreach ($index_list as $at => $item) {
            $tmp   = [];
            $tmp[] = substr($at, 0, 4) . '年' . substr($at, 4) . '月';//月份
            $value = $created = $updated = [];
            foreach ($item as $child) {
                $value[] = $child['value'];
                if (!isset($created[$at]))
                    $created[$at] = $child['created_at'];
                if (!isset($updated[$at]))
                    $updated[$at] = $child['updated_at'];
            }
            $tmp    = array_merge($tmp, $value);
            $tmp    = array_merge($tmp, $created);
            $tmp    = array_merge($tmp, $updated);
            if($this->getAuth()){
                $tmp[]  = '<input type="button" value="编辑" class="layui-btn layui-btn-sm data-btn"  data-at="' . $at . '">';
            } else{
                $tmp[] = '';
            }
            $body[] = $tmp;
        }
        $table = [
            'head' => $head,
            'body' => $body,
        ];
        return $table;
    }
}
